<template>
  <page-container class="set-ai-early-warning">
    <supper-select @change="supperSelectChange" :options="supperSelectOptions"></supper-select>
    <a-button @click="setUpModal" class="set-up-btn">执行全部预警</a-button>
    <a-button @click="addModal" class="add-btn" type="primary">新增规则</a-button>
    <set-rule-modal
      v-model:visible="ruleModalVisible"
      :status="ruleModalStatus"
      :rule="currentRuleData"
      :errMsg="ruleErrMsg"
      @commit="ruleModalCommit"
    ></set-rule-modal>
    <start-up-modal
      v-model:visible="startUpModalVisible"
      :models="models"
      @commit="startUpModalCommit"
      @stateUpdate="stateUpdate"
    ></start-up-modal>

    <a-table
      :dataSource="dataSource"
      :columns="columns"
      bordered
      style="margin-top: 20px"
      :pagination="{ total: total }"
    >
      <template #rules="{ text: rules }" class="rules-row">
        <a-table
          :columns="[
            {
              dataIndex: 'number',
              slots: { customRender: 'number' },
              width: 100,
              align: 'center',
            },
            {
              dataIndex: 'rule',
              key: 'rule',
              slots: { customRender: 'rule' },
            },
            {
              key: 'action',
              slots: { customRender: 'action' },
            },
          ]"
          :data-source="rules"
          :bordered="false"
          :pagination="false"
          :showHeader="false"
        >
          <template #number="{ index }">规则{{ index + 1 }}</template>
          <template #rule="{ record }">
            <rule-item :ruleData="record"></rule-item>
          </template>
          <template #action="{ record }">
            <span style="padding-right: 15px">
              <a @click="removeRule(record)">删除</a>
              <a-divider type="vertical" />
              <a class="ant-dropdown-link" @click="openRule(record)">
                编辑
                <down-outlined />
              </a>
            </span>
          </template>
          <template #operation>
            <span style="padding-right: 15px">执行预警</span>
          </template>
        </a-table>
      </template>
    </a-table>
  </page-container>
</template>

<script lang="ts">
import { defineComponent, ref, onMounted, reactive, toRaw, createVNode, h } from 'vue';
import SupperSelect from '@/components/supper-select/index.vue';
import { getParamsCodes } from '@/components/supper-select/index.js';
import RuleItem from '@/views/magic-cube/method-mode/components/rule-item/index.vue';
import StartUpModal from '@/views/magic-cube/method-mode/set-ai-early-warning/components/start-up-modal/index.vue';
import SetRuleModal from '@/views/magic-cube/method-mode/set-ai-early-warning/components/set-rule-modal/index.vue';
import { addSjMode, deleteSjRule, updateSjRule, querySjRule } from '@/api/magic-cube/event-warning';
import {
  ruleItemState,
  tableItemState,
} from '@/views/magic-cube/method-mode/set-ai-early-warning/js/typing';
import { message, Modal } from 'ant-design-vue';
import { ExclamationCircleOutlined } from '@ant-design/icons-vue';
import MTag from '@/components/m-tag/index.vue';

const initRuleState: ruleItemState = {
  ruleId: '', // 规则id
  modelId: '', // 模型id
  period: 'D', // 周期（日-D，周-W，月-M）
  type: 'T', // 规则增长类型（T-同比，H-环比，N-数值）
  level1: 80, // 红色预警
  level2: 60, // 橙色预警
  level3: 40, // 黄色预警
  level4: 20, // 蓝色预警
};

const classifyTypeMap = {
  1: 'ai',
  2: 'jq',
  3: 'fk',
};
export default defineComponent({
  components: {
    SupperSelect,
    RuleItem,
    SetRuleModal,
    StartUpModal,
  },
  setup() {
    const dataSource = ref<Array<tableItemState>>([]);
    const ruleModalVisible = ref(false);
    const startUpModalVisible = ref(false);
    const currentRuleData = ref<ruleItemState>({ ...initRuleState });
    const ruleModalStatus = ref(0); // 0 新增 1 编辑
    const ruleErrMsg = ref([]);
    const params = reactive({
      classifyCodes: '',
      callSummaryCodes: '',
      dealSummaryCodes: '',
    });
    const supperSelectOptions = [
      {
        type: 'jq',
        visible: false,
      },
      {
        type: 'fk',
        visible: false,
      },
      {
        type: 'xqdw',
        visible: false,
      },
    ];
    const total = ref(0);
    const models = ref('');
    const setUpModalState = ref(false);

    const columns = [
      {
        title: '模型名称',
        dataIndex: 'name',
        key: 'name',
        customRender: ({ text, record }) => {
          const type = classifyTypeMap[record.classifyType];
          const obj = {
            props: {} as any,
            children: h(MTag, { type }, text),
          };
          return obj;
        },
      },
      {
        title: '归属辖区',
        dataIndex: 'xqdwName',
        key: 'xqdwName',
        customRender: ({ text }) => {
          const obj = {
            children: text,
            props: {} as any,
          };
          return obj;
        },
      },
      {
        title: '规则详情',
        dataIndex: 'rules',
        key: 'rules',
        slots: { customRender: 'rules' },
      },
      {
        title: '操作',
        dataIndex: 'operation',
        key: 'operation',
        slots: { customRender: 'operation' },
        customRender: ({ text, record, index }) => {
          const obj = {
            children: h(
              'a',
              {
                onClick: args => {
                  console.log('执行预警 click ', index, record);
                  startUpModalVisible.value = true;
                  models.value = record.modelId;
                },
              },
              '执行预警',
            ),
            props: {} as any,
          };
          return obj;
        },
      },
    ];
    //周期类型数据转换
    const setPeriod = (period: string): string => {
      let s = '';
      switch (period) {
        case 'D':
          s = '每日';
          break;
        case 'W':
          s = '每周';
          break;
        case 'M':
          s = '每月';
          break;
      }
      return s;
    };

    // supperSelect
    const supperSelectChange = (list: Array<string>) => {
      const { ai, jq, fk } = getParamsCodes(list);
      params.classifyCodes = ai;
      params.callSummaryCodes = jq;
      params.dealSummaryCodes = fk;
      getRuleList();
    };

    const addModal = () => {
      //   if (!params.classifyCodes) {
      //     message.info('请先选择分类');
      //     return false;
      //   }
      ruleErrMsg.value = [];
      currentRuleData.value = { ...initRuleState };
      ruleModalStatus.value = 0;
      ruleModalVisible.value = true;
    };
    const setUpModal = () => {
      startUpModalVisible.value = true;
      models.value = '';
    };

    // 获取模型列表
    const getRuleList = () => {
      querySjRule({
        ...toRaw(params),
        classifyTypes: '1',
      })
        .then(res => {
          if (res.code === 200) {
            dataSource.value = res.data.details;
            total.value = res.data.count;
          }
        })
        .catch(err => {
          console.log('getRuleList', err);
        });
    };

    // 添加接口
    const saveModalInfo = (rule, param) => {
      const paramsData = {
        ...rule,
        ...param,
      };
      addSjMode(paramsData)
        .then(res => {
          if (res.code === 200 && res.data === 1) {
            ruleModalVisible.value = false;
            message.success('添加成功');
            getRuleList();
          } else {
            message.info('添加失败');
            ruleErrMsg.value = res.data;
          }
        })
        .catch(err => {
          console.log('getRuleList', err);
        });
    };

    // 删除
    const removeRule = record => {
      Modal.confirm({
        title: '提示',
        icon: createVNode(ExclamationCircleOutlined),
        content: '是否删除该规则？',
        okText: '确认',
        cancelText: '取消',
        onOk() {
          deleteRule(record.modelId, record.ruleId);
        },
      });
    };

    // 删除规则接口
    const deleteRule = (modelId, ruleId) => {
      const paramsData = {
        modelId,
        ruleId,
      };
      deleteSjRule(paramsData)
        .then(res => {
          if (res.code === 200 && res.data === 1) {
            message.success('删除成功');
            getRuleList();
          } else {
            message.info('删除失败');
          }
        })
        .catch(err => {
          console.log('deleteSjRule', err);
        });
    };

    // 修改规则接口
    const updateRule = rule => {
      updateSjRule({ ...rule })
        .then(res => {
          if (res.code === 200 && res.data === 1) {
            ruleModalVisible.value = false;
            message.success('修改成功');
            getRuleList();
          } else {
            message.info('修改失败');
            ruleErrMsg.value = res.data;
          }
        })
        .catch(err => {
          console.log('updateRule', err);
        });
    };

    // 点击编辑按钮
    const openRule = (record: ruleItemState) => {
      ruleModalStatus.value = 1;
      ruleErrMsg.value = [];
      currentRuleData.value = { ...toRaw(record) };
      ruleModalVisible.value = true;
    };

    // 添加或修改保存
    const ruleModalCommit = (rule, status, params) => {
      status ? updateRule(rule) : saveModalInfo(rule, params);
    };
    const startUpModalCommit = () => {
      startUpModalVisible.value = false;
      setUpModalState.value = true;
    };
    const stateUpdate = state => {
      setUpModalState.value = state;
    };
    onMounted(() => {
      getRuleList();
    });
    return {
      supperSelectChange,
      supperSelectOptions,
      dataSource,
      total,
      columns,
      setPeriod,
      addModal,
      saveModalInfo,
      ruleModalVisible,
      startUpModalVisible,
      currentRuleData,
      ruleModalStatus,
      ruleModalCommit,
      removeRule,
      openRule,
      ruleErrMsg,
      models,
      startUpModalCommit,
      setUpModal,
      setUpModalState,
      stateUpdate,
    };
  },
});
</script>

<style scoped lang="less">
.set-ai-early-warning {
  position: relative;
  .set-up-btn {
    position: absolute;
    top: 80px;
    right: 150px;
  }
  .add-btn {
    position: absolute;
    top: 80px;
    right: 50px;
  }
}
</style>
